package com.sxhalo.manage.web.action;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.*;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.BeanUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sxhalo.manage.map.*;
import com.sxhalo.manage.service.IBaseService;
import com.sxhalo.manage.utils.DateUtil;
import com.sxhalo.manage.utils.Pager;
import com.sxhalo.manage.web.form.CalendarForm;
import com.sxhalo.manage.web.form.TaskForm;

public class TaskAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	private int draw = 1;

	private int start = 0;

	private int length = 20;

	private TaskForm task;

	// 将会被Struts2序列化为JSON字符串的对象
	private Map<String, Object> dataMap;
    
    private List dataList;

	// 业务层
	private IBaseService<Task> myService;
	
	private IBaseService<SysUsers> userService;
	
	private IBaseService<Projects> projectService;
	
	private IBaseService<TaskPriority> priorityService;
	
	private IBaseService<TaskStatus> statusService;
	
	private IBaseService<TaskType> typeService;

	public int getDraw() {
		return draw;
	}

	public void setDraw(int draw) {
		this.draw = draw;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public TaskForm getTask() {
		return task;
	}

	public void setTask(TaskForm task) {
		this.task = task;
	}

	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public List getDataList() {
		return dataList;
	}

	public void setDataList(List dataList) {
		this.dataList = dataList;
	}

	public IBaseService<Task> getMyService() {
		return myService;
	}

	public void setMyService(IBaseService<Task> myService) {
		this.myService = myService;
	}

	public IBaseService<SysUsers> getUserService() {
		return userService;
	}

	public void setUserService(IBaseService<SysUsers> userService) {
		this.userService = userService;
	}

	public IBaseService<Projects> getProjectService() {
		return projectService;
	}

	public void setProjectService(IBaseService<Projects> projectService) {
		this.projectService = projectService;
	}

	public IBaseService<TaskPriority> getPriorityService() {
		return priorityService;
	}

	public void setPriorityService(IBaseService<TaskPriority> priorityService) {
		this.priorityService = priorityService;
	}

	public IBaseService<TaskStatus> getStatusService() {
		return statusService;
	}

	public void setStatusService(IBaseService<TaskStatus> statusService) {
		this.statusService = statusService;
	}

	public IBaseService<TaskType> getTypeService() {
		return typeService;
	}

	public void setTypeService(IBaseService<TaskType> typeService) {
		this.typeService = typeService;
	}

	/**
	 * 构造方法
	 */
	public TaskAction() {
		// 初始化Map对象
		dataMap = new HashMap<String, Object>();
	}
	
	public String getForm(){
		List<Projects> plist = projectService.findAll();
		List<Task> mlist = new ArrayList<Task>();
		int comid = 0;
		if(plist.size()>0){
			comid = plist.get(0).getCompany().getCompanyId();
			mlist = myService.findList("taskProject", plist.get(0));
		}
		List<SysUsers> ulist = getCompanyUser(comid);
		try {
			Task entity = myService.findById(task.getTaskId());
			task.setTaskName(entity.getTaskName());
			task.setTaskParent(entity.getTaskParent());
			task.setTaskProject(entity.getTaskProject().getProjectId());
			task.setTaskOwner(entity.getTaskOwner().getUserId());
			task.setTaskStartDate(DateUtil.format(entity.getTaskStartDate()));
			task.setTaskDuration(entity.getTaskDuration());
			task.setTaskDurationType(entity.getTaskDurationType());
			task.setTaskHoursWorked(entity.getTaskHoursWorked());
			task.setTaskEndTime(DateUtil.format(entity.getTaskEndTime()));
			task.setTaskStatus(entity.getTaskStatus().getTaskStatusId());
			task.setTaskPriority(entity.getTaskPriority().getTaskPriorityId());
			task.setTaskPercentComplete(entity.getTaskPercentComplete());
			task.setTaskDescription(entity.getTaskDescription());
			task.setTaskDynamic(entity.getTaskDynamic());
			task.setTaskCreator(entity.getTaskCreator());
			task.setTaskAccess(entity.getTaskAccess());
			task.setTaskDepartments(entity.getTaskDepartments());
			task.setTaskCantacts(entity.getTaskCantacts());
			task.setTaskType(entity.getTaskType().getTaskTypeId());
			task.setTaskNotify(entity.getTaskNotify());
			//下拉取值
			Projects project = projectService.findById(entity.getTaskProject());
			ulist = getCompanyUser(project.getCompany().getCompanyId());
			mlist = myService.findList("taskProject", entity.getTaskProject());
			mlist.remove(entity);
		} catch (Exception re) {
			
		}
		ActionContext.getContext().put("plist", plist);
		ActionContext.getContext().put("ulist", ulist);
		ActionContext.getContext().put("mlist", mlist);
		ActionContext.getContext().put("ilist", priorityService.findAll());
		ActionContext.getContext().put("slist", statusService.findAll());
		ActionContext.getContext().put("tlist", typeService.findAll());
		// 返回结果
		return SUCCESS;
	}
	
    public String getEntity() {
		try {
			Task entity = myService.findById(task.getTaskId());
			task.setTaskName(entity.getTaskName());
			task.setTaskParent(entity.getTaskParent());
			task.setTaskProject(entity.getTaskProject().getProjectId());
			task.setTaskOwner(entity.getTaskOwner().getUserId());
			task.setTaskStartDate(DateUtil.format(entity.getTaskStartDate()));
			task.setTaskDuration(entity.getTaskDuration());
			task.setTaskDurationType(entity.getTaskDurationType());
			task.setTaskHoursWorked(entity.getTaskHoursWorked());
			task.setTaskEndTime(DateUtil.format(entity.getTaskEndTime()));
			task.setTaskStatus(entity.getTaskStatus().getTaskStatusId());
			task.setTaskPriority(entity.getTaskPriority().getTaskPriorityId());
			task.setTaskPercentComplete(entity.getTaskPercentComplete());
			task.setTaskDescription(entity.getTaskDescription());
			task.setTaskDynamic(entity.getTaskDynamic());
			task.setTaskCreator(entity.getTaskCreator());
			task.setTaskAccess(entity.getTaskAccess());
			task.setTaskDepartments(entity.getTaskDepartments());
			task.setTaskCantacts(entity.getTaskCantacts());
			task.setTaskType(entity.getTaskType().getTaskTypeId());
			task.setTaskNotify(entity.getTaskNotify());
			task.setTaskProjectName(entity.getTaskProject().getProjectName());
			task.setTaskOwnerName(entity.getTaskOwner().getSysUserinfo().getUserinfoTruename());
			task.setTaskStatusName(entity.getTaskStatus().getTaskStatusName());
			task.setTaskPriorityName(entity.getTaskPriority().getTaskPriorityName());
			task.setTaskTypeName(entity.getTaskType().getTaskTypeName());
			Task taskParent = myService.findById(task.getTaskParent());
			task.setTaskParentName(taskParent.getTaskName());
		} catch (Exception re) {
			
		}
		// 返回结果
		return SUCCESS;
	}

    public String getGridData() {
		// dataMap中的数据将会被Struts2转换成JSON字符串，所以这里要先清空其中的数据
		dataMap.clear();
		// 获取数据
		try {
			String where = "";
			String projectId =  ServletActionContext.getRequest().getParameter("proid");
			if(projectId!=null && !projectId.equals("")){
				where += " taskProject = "+ projectId; 
			}
			String tabid =  ServletActionContext.getRequest().getParameter("tabid");
			if(null!=tabid){
				where += getWhereForTabid(tabid);
			}
			int page = start == 0 ? 1 : start / length + 1;
			int size = length < 0 ? Integer.MAX_VALUE : length;
			Pager<Task> list =myService.findPagerList(page, size, where, "");
			dataMap.put("draw", draw);
			dataMap.put("recordsTotal", list.getTotal());
			dataMap.put("recordsFiltered", list.getTotal());
			dataMap.put("data", copyList(list.getList()));
		} catch (Exception re) {
			dataMap.put("data", re.getMessage());
		}
		// 返回结果
		return SUCCESS;
	}
  
    public String getAllData() {
		// 获取数据
        try {
        	String projectId =  ServletActionContext.getRequest().getParameter("proid");
        	List<Task> list = myService.findList("taskProject.projectId",Integer.parseInt(projectId));
        	dataList = copyList(list);
        } catch (Exception re) {
			
		}
		// 返回结果
		return SUCCESS;
	}
    public String addEntity() {
    	// 清空dataMap中的数据
    	dataMap.clear();
    	try {
    		Timestamp startDate = Timestamp.valueOf(task.getTaskStartDate());
    		Timestamp endDate = Timestamp.valueOf(task.getTaskEndTime());
    		
			Task entity = new Task();
			entity.setTaskName(task.getTaskName());
			entity.setTaskParent(task.getTaskParent());
			Projects projects = new Projects();
			projects.setProjectId(task.getTaskProject());
			entity.setTaskProject(projects);
			SysUsers user = new SysUsers();
			user.setUserId(task.getTaskOwner());
			entity.setTaskOwner(user);
			entity.setTaskStartDate(startDate);
			entity.setTaskDuration(task.getTaskDuration());
			entity.setTaskDurationType(task.getTaskDurationType());
			entity.setTaskHoursWorked(task.getTaskHoursWorked());
			entity.setTaskEndTime(endDate);
			TaskStatus taskStatus = new TaskStatus();
			taskStatus.setTaskStatusId(task.getTaskStatus());
			entity.setTaskStatus(taskStatus);
			TaskPriority taskPriority = new TaskPriority();
			taskPriority.setTaskPriorityId(task.getTaskPriority());
			entity.setTaskPriority(taskPriority);
			entity.setTaskPercentComplete(task.getTaskPercentComplete());
			entity.setTaskDescription(task.getTaskDescription());
			entity.setTaskDynamic(task.getTaskDynamic());
			entity.setTaskCreator(task.getTaskCreator());
			entity.setTaskAccess(task.getTaskAccess());
			entity.setTaskDepartments(task.getTaskDepartments());
			entity.setTaskCantacts(task.getTaskCantacts());
			TaskType taskType = new TaskType();
			taskType.setTaskTypeId(task.getTaskType());
			entity.setTaskType(taskType);
			entity.setTaskNotify(task.getTaskNotify());
			myService.save(entity);
		} catch (Exception re) {
			return ERROR;
		}
		// 返回结果
		return SUCCESS;
	}
	public String editEntity() {
		// 清空dataMap中的数据
		dataMap.clear();
		try {
			Timestamp startDate = Timestamp.valueOf(task.getTaskStartDate());
    		Timestamp endDate = Timestamp.valueOf(task.getTaskEndTime());
			
			Task entity = myService.findById(task.getTaskId());
			entity.setTaskName(task.getTaskName());
			entity.setTaskParent(task.getTaskParent());
			Projects projects = new Projects();
			projects.setProjectId(task.getTaskProject());
			entity.setTaskProject(projects);
			SysUsers user = new SysUsers();
			user.setUserId(task.getTaskOwner());
			entity.setTaskOwner(user);
			entity.setTaskStartDate(startDate);
			entity.setTaskDuration(task.getTaskDuration());
			entity.setTaskDurationType(task.getTaskDurationType());
			entity.setTaskHoursWorked(task.getTaskHoursWorked());
			entity.setTaskEndTime(endDate);
			TaskStatus taskStatus = new TaskStatus();
			taskStatus.setTaskStatusId(task.getTaskStatus());
			entity.setTaskStatus(taskStatus);
			TaskPriority taskPriority = new TaskPriority();
			taskPriority.setTaskPriorityId(task.getTaskPriority());
			entity.setTaskPriority(taskPriority);
			entity.setTaskPercentComplete(task.getTaskPercentComplete());
			entity.setTaskDescription(task.getTaskDescription());
			entity.setTaskDynamic(task.getTaskDynamic());
			entity.setTaskCreator(task.getTaskCreator());
			entity.setTaskAccess(task.getTaskAccess());
			entity.setTaskDepartments(task.getTaskDepartments());
			entity.setTaskCantacts(task.getTaskCantacts());
			TaskType taskType = new TaskType();
			taskType.setTaskTypeId(task.getTaskType());
			entity.setTaskType(taskType);
			entity.setTaskNotify(task.getTaskNotify());
			myService.update(entity);
			dataMap.put("data", true);
		} catch (Exception re) {
			dataMap.put("data", re.getMessage());
		}
		// 返回结果
		return SUCCESS;
	}

	public String delEntity() {
		// 清空dataMap中的数据
        dataMap.clear();
		try {
			Task entity = myService.findById(task.getTaskId());
				if(myService.delete(entity)){
					dataMap.put("valid", true);
				} else {
					dataMap.put("valid", false);
				}
			} catch (Exception re) {
				dataMap.put("valid", false);
			}
		// 返回结果
		return SUCCESS;
	}
	
	//日历查询
	public String getCalendar() {
		String userName = ServletActionContext.getRequest().getRemoteUser();
		SysUsers entity = userService.find("userUsername", userName);
		List<Task> list = myService.findList("taskOwner.userId", entity.getUserId());

    	dataList = copyToCalendar(list);
		// 返回结果
		return SUCCESS;
	}
	
	private List<TaskForm> copyList(List<Task> list){
		List<TaskForm> data = new ArrayList<TaskForm>();
    	for(Task po:list){
    		TaskForm vo = new TaskForm();
    		vo.setTaskId( po.getTaskId());
    		vo.setTaskName(po.getTaskName());
    		vo.setTaskPercentComplete(po.getTaskPercentComplete());
    		vo.setTaskDescription(po.getTaskDescription());
    		vo.setTaskDuration(po.getTaskDuration());
    		vo.setTaskProjectName(po.getTaskProject().getProjectName());
    		vo.setTaskOwnerName(po.getTaskOwner().getSysUserinfo().getUserinfoTruename());
    		vo.setTaskEndTime(po.getEndTime());
    		vo.setTaskStartDate(po.getStartDate());
    		vo.setTaskPriorityName(po.getTaskPriority().getTaskPriorityName());
    		data.add(vo);
    	}
    	return data;
	}
	
	private List<CalendarForm> copyToCalendar(List<Task> list){
		List<CalendarForm> att = new ArrayList<CalendarForm>();
		for(Task c:list){
			CalendarForm v = new CalendarForm();
			v.setTaskId(c.getTaskId());
	        v.setTitle(c.getTaskName());
	        v.setStart(c.getTaskStartDate());
	        v.setEnd(c.getTaskEndTime());
	        v.setClassName("label-success");
			att.add(v);
		}
		return att;
	}
	//日历查询end

	public List<SysUsers> getCompanyUser(Integer companyId) {
		List<SysUsers> list = new ArrayList<SysUsers>();
		List<SysUsers> users = userService.findAll();
		for (SysUsers u : users) {
			if (u.getSysUserinfo().getCompany().getCompanyId() == companyId) {
				list.add(u);
			}
		}
		return list;
	}
	
	public String getWhereForTabid(String tabid){
		Calendar cal=Calendar.getInstance();
		cal.add(Calendar.DATE, -7);
		String taskEndTime="";
		try {
			taskEndTime = DateUtil.format(cal.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		String userName = ServletActionContext.getRequest().getRemoteUser();
		SysUsers entity = userService.find("userUsername", userName);
		String where = "";
		int key = Integer.parseInt(tabid);
		switch (key) {
		case 1:
			where += " taskPercentComplete < 100";
			break;
		case 2:
			where += " taskPercentComplete = 100";
			break;
		case 3:
			where += " taskPercentComplete < 100 and taskOwner.userId="+entity.getUserId();
			break;
		case 4:
			where += " taskPercentComplete = 100 and taskOwner.userId="+entity.getUserId();
			break;
		case 5:
			where += " taskPercentComplete = 100 and taskEndTime > " + "'"+taskEndTime+"'";
			break;
		default:
			break;
		}
		return where;
	}
}
